/*
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-30 16:12:30
 * @LastEditTime: 2022-05-30 21:34:52
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description: 
 */
const arr = [
  { id: 1, name: '部门 1', pid: 0 },
  { id: 2, name: '部门 2', pid: 1 },
  { id: 3, name: '部门 3', pid: 1 },
  { id: 4, name: '部门 4', pid: 3 },
  { id: 5, name: '部门 5', pid: 4 },
]
function generateTree(arr) {
  const map = {}


  arr.forEach(item => {
    map[item.id] = item
  });


  const newArr = []

  arr.forEach(item => {
    
    const parent = map[item.pid]

    if (parent){

      if(!parent.children) parent.children = []
      parent.children.push(item)

    }else{
      newArr.push(item)
    }
  })
  return newArr
}
console.log(generateTree(arr));